﻿using Dapper;
using Microsoft.EntityFrameworkCore;
using System.Data.Common;
using System.Reflection;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Fms;
using VisionCloud.Core.Model.Ms;
using VisionCloud.Core.Model.Rs;
using VisionCloud.Core.Model.Schedule;
using VisionCloud.Core.Model.Sys;

namespace VisionCloud.Core
{
    public partial class BlueDbContext : DbContext
    {
        public BlueDbContext(DbContextOptions<BlueDbContext> options) : base(options)
        {
            //this.Database.SetCommandTimeout(3000);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<MsHouseMapPoint>().HasKey(x => new { x.HouseMapId, x.PointId, x.PointIndex });
            modelBuilder.Entity<MsMeasureItem>().HasKey(x => new { x.HouseMapId, x.PointId, x.ItemId });
            modelBuilder.Entity<MsMeasureTemplate>().HasKey(x => new { x.HouseMapId, x.Id });
            modelBuilder.Entity<MsPointTypeMeasureItem>().HasKey(x => new { x.MsPointTypeMeasureItemId });
            modelBuilder.Entity<MsTaskStandard>().HasKey(x => new { x.Id, x.MsPointTypeId });
            modelBuilder.Entity<MsProjectStandardMeasureItemValue>().HasKey(x => new { x.MsProjectStandardMeasureItemValueId });
            modelBuilder.Entity<MsManualMeasureReport>().HasKey(x => new { x.TaskId, x.PointIndex });
            modelBuilder.Entity<MsDataSnyc>().HasKey(x => new { x.Id, x.ItemId });

            modelBuilder.Entity<SysDevice>().HasIndex(t => new { t.EncryptedDogNumber, t.EncryptedDogType });
            modelBuilder.Entity<SysDevice>().HasIndex(t => t.DeviceNumber);

            modelBuilder.Entity<MsProject>().HasIndex(t => t.Name);
            modelBuilder.Entity<MsProject>().HasIndex(t => t.ProjectId);
            //modelBuilder.Entity<MsProject>().HasMany(t => t.SysUserProject);

            modelBuilder.Entity<MsReport>().HasIndex(t => t.TaskReportId).IsUnique();
            modelBuilder.Entity<MsReport>().HasIndex(t => t.TaskId);
            modelBuilder.Entity<MsReport>().HasIndex(t => t.YunProjectGuid);
            modelBuilder.Entity<MsReport>().HasIndex(t => t.YunTaskId);

            modelBuilder.Entity<MsUpdate>().HasIndex(t => t.UpdateId);

            modelBuilder.Entity<MsUserToProject>().HasIndex(t => t.YunProjectGuid);
            modelBuilder.Entity<MsUserToProject>().HasIndex(t => t.YunUserGuid);

            modelBuilder.Entity<MsUserToUser>().HasIndex(t => t.YunUserGuidLeft);
            modelBuilder.Entity<MsUserToUser>().HasIndex(t => t.YunUserGuidRight);

            modelBuilder.Entity<SysDeviceUser>().HasIndex(t => t.DeviceGuid);
            modelBuilder.Entity<SysDeviceUser>().HasIndex(t => t.UserGuid);

            modelBuilder.Entity<SysUser>().HasIndex(t => t.Email).IsUnique();

            modelBuilder.Entity<MsProjectEditLog>().HasIndex(t => t.ProjectId);

            modelBuilder.Entity<MsTaskDotCloud>().HasIndex(t => t.FileId);
            modelBuilder.Entity<MsSProgressAnalysis>().HasIndex(t => t.MsProgressAnalysisGuid);

            modelBuilder.Entity<MsProjectAlgorithm>().HasKey(x => new { x.ProjectId, x.AlgorithmId });

            modelBuilder.Entity<SysNotifyUser>().HasKey(x => new { x.NotificationId, x.UserId });

            modelBuilder.Entity<SysNotification>().HasIndex(x => x.Id);

            modelBuilder.Entity<MsPointCompleted>().HasKey(x => new { x.TaskId, x.PointIndex });

            modelBuilder.Entity<MsDotCloudCollect>().HasKey(x => new { x.TaskId, x.PointIndex });

            modelBuilder.Entity<SysUserDeviceTrace>().HasKey(x => new { x.DeviceId, x.DeviceNumber, x.CreatedDate });

            modelBuilder.Entity<MsTaskWxMessage>(enpty => { enpty.Property(e => e.Message).HasColumnType("jsonb"); });

            #region Schedule Module

            modelBuilder.Entity<RsWorkOrder>(x =>
            {
                x.HasIndex(a => a.Id);
            });

            #endregion Schedule Module

            base.OnModelCreating(modelBuilder);
            SetDbView(modelBuilder);
            modelBuilder.HasPostgresExtension("uuid-ossp");
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }

        private void SetDbView(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ProjectProgressView>().HasNoKey().ToView("vw_progress");
            modelBuilder.Entity<ProjectQualificationRateView>().HasNoKey().ToView("vw_project_qualification_rate");
            modelBuilder.Entity<DeviceLastAddressView>().HasNoKey().ToView("vw_device_last_address");
        }

        #region MS

        public virtual DbSet<MsFileStatus> MsFileStatus { get; set; }

        //public virtual DbSet<MsDevice> MsDevices { get; set; }
        public virtual DbSet<MsProject> MsProjects { get; set; }

        public virtual DbSet<MsHouseMapDetails> MsHouseMapDetails { get; set; }
        public virtual DbSet<MsTask> MsTasks { get; set; }
        public virtual DbSet<MsReport> MsReports { get; set; }
        public virtual DbSet<MsProjectRobot> MsProjectRobots { get; set; }

        public virtual DbSet<MsUserToProject> MsUserToProjects { get; set; }
        public virtual DbSet<MsUserToUser> MsUserToUsers { get; set; }
        public virtual DbSet<MsUpdate> MsUpdates { get; set; }

        public virtual DbSet<MsTaskMeasureItemTemplate> MsTaskMeasureItemTemplates { get; set; }
        public virtual DbSet<MsProjectStandard> MsProjectStandards { get; set; }
        public virtual DbSet<MsHouseMap> MsHouseMaps { get; set; }

        public virtual DbSet<MsTaskReport> MsTaskReport { get; set; }

        public virtual DbSet<MeasurementItem> MeasurementItems { get; set; }

        public virtual DbSet<MSTaskPoint2ManualMeasurement> MSTaskPoint2ManualMeasurements { get; set; }

        public virtual DbSet<TaskPoints> TaskPointss { get; set; }
        public virtual DbSet<MsHouseMapPoint> MsHouseMapPoints { get; set; }
        public virtual DbSet<MsMeasureItem> MsMeasureItems { get; set; }
        public virtual DbSet<MsMeasureTemplate> MsMeasureTemplates { get; set; }

        public virtual DbSet<MsDevice> MsDevices { get; set; }

        public virtual DbSet<MsPointType> MsPointTypes { get; set; }
        public virtual DbSet<MsProjectStandardMeasureItem> MsProjectStandardMeasureItems { get; set; }
        public virtual DbSet<MsProjectStandardMeasureItemValue> MsProjectStandardMeasureItemValues { get; set; }

        public virtual DbSet<MsPointTypeMeasureItem> MsPointTypeMeasureItems { get; set; }
        public virtual DbSet<MsTaskStandard> MsTaskStandards { get; set; }

        public virtual DbSet<MsManualMeasureReport> MsManualMeasureReports { get; set; }

        public virtual DbSet<MsAlgorithmParamTemplate> MsAlgorithmParamTemplates { get; set; }
        public virtual DbSet<MsAlgorithmParamTemplateItem> MsAlgorithmParamTemplateItems { get; set; }

        public virtual DbSet<MsManualMeasureSummaryItems> MsManualMeasureSummaryItems { get; set; }

        /// <summary>
        /// 质量分析数据
        /// </summary>
        public virtual DbSet<MsSQualityAnalysis> MsSQualityAnalysis { get; set; }

        public virtual DbSet<MsSProgressAnalysis> MsSProgressAnalysis { get; set; }

        public virtual DbSet<MsSPersonnelEfficiency> MsSPersonnelEfficiency { get; set; }

        public virtual DbSet<MsProjectEditLog> MsProjectEditLogs { get; set; }

        public virtual DbSet<CSMSTask> CSMSTasks { get; set; }

        public virtual DbSet<MsTaskDotCloud> MsTaskDotCloud { get; set; }
        public virtual DbSet<ProjectProgressView> ProjectProgressView { get; set; }
        public virtual DbSet<ProjectQualificationRateView> ProjectQualificationRateView { get; set; }

        public virtual DbSet<DeviceLastAddressView> DeviceLastAddressView { get; set; }

        public virtual DbSet<MsProjectAlgorithm> MsProjectAlgorithms { get; set; }

        public virtual DbSet<MsHouseMapBuildingFloor> MsHouseMapBuildingFloor { get; set; }

        public virtual DbSet<MsPointCompleted> MsPointCompleteds { get; set; }

        /// <summary>
        /// 诊断报告表
        /// </summary>
        public virtual DbSet<MsDiagnosticReport> MsDiagnosticReports { get; set; }

        public virtual DbSet<MsTaskDotCloudBatch> MsTaskDotCloudBatch { get; set; }

        public virtual DbSet<MsTaskWxMessage> MsTaskWxMessage { get; set; }

        /// <summary>
        /// 点云上传记录
        /// </summary>
        public virtual DbSet<MsDotCloudUpload> DotCloudUpload { get; set; }

        /// <summary>
        /// 点云采集记录
        /// </summary>
        public virtual DbSet<MsDotCloudCollect> MsDotCloudCollect { get; set; }

        #endregion MS

        #region Sys

        public virtual DbSet<SysMenu> SysMenus { get; set; }
        public virtual DbSet<SysMenuFunc> SysMenuFuncs { get; set; }
        public virtual DbSet<SysRolePermission> SysRolePermissions { get; set; }
        public virtual DbSet<SysRole> SysRoles { get; set; }
        public virtual DbSet<SysUser> SysUsers { get; set; }
        public virtual DbSet<SysUserRole> SysUserRoles { get; set; }
        public virtual DbSet<SysLog> SysLog { get; set; }
        public virtual DbSet<SysDevice> SysDevices { get; set; }
        public virtual DbSet<SysDeviceUser> SysDeviceUsers { get; set; }

        public virtual DbSet<SysOrg> SysOrg { get; set; }
        public virtual DbSet<SysCodeFlow> SysCodeFlow { get; set; }
        public virtual DbSet<SysOrgUser> SysOrgUser { get; set; }

        public virtual DbSet<SysFile> SysFiles { get; set; }

        public virtual DbSet<SysUserProject> SysUserProject { get; set; }

        public virtual DbSet<SysDeviceUnlock> SysDeviceUnlock { get; set; }
        public virtual DbSet<SysReleaseRecord> SysReleaseRecords { get; set; }
        public virtual DbSet<SysUserUpdateRecord> SysUserUpdateRecords { get; set; }

        public virtual DbSet<SysNotification> SysNotifications { get; set; }

        public virtual DbSet<SysNotifyUser> SysNotifyUsers { get; set; }

        public virtual DbSet<SysDistrict> SysDistricts { get; set; }

        public virtual DbSet<SysWxMessage> SysWxMessages { get; set; }

        public virtual DbSet<SysUserDeviceTrace> SysUserDeviceTraces { get; set; }

        public virtual DbSet<SysPackFileUpload> SysPackFileUploads { get; set; }

        #endregion Sys

        #region Schedule Module

        public virtual DbSet<RsWorkOrder> WorkOrders { get; set; }

        public virtual DbSet<MsProjectBuilding> MsProjectBuildings { get; set; }

        public virtual DbSet<RsRobotMeasureData> RsRobotMeasureData { get; set; }

        #endregion Schedule Module

        #region Fms

        public virtual DbSet<FmsProjectBuildingFloor> FmsProjectBuildingFloor { get; set; }

        #endregion Fms

        #region Rs

        public virtual DbSet<RsWorkOrder> RsWorkOrder { get; set; }

        public virtual DbSet<RsWorkOrderMap> RsWorkOrderMap { get; set; }

        public virtual DbSet<RsWorkOrderOrg> RsWorkOrderOrg { get; set; }

        #endregion Rs

        /// <summary>
        /// sql语句执行方法
        /// </summary>
        /// <param name="ExecuteStr">sql语句</param>
        /// <param name="param">参数</param>
        /// <returns>返回受影响的行数</returns>
        public static async Task<int> ExecuteAsync(string ExecuteStr, object param = null)
        {
            using (DbConnection con = BlueDbContextFactory.GetDbConnection())
            {
                if (param == null)
                    return await con.ExecuteAsync(ExecuteStr);
                else
                    return await con.ExecuteAsync(ExecuteStr, param);
            }
        }
    }
}